<?php

class Service extends CI_Model {

    const Statustrue = True;
    const Statusflase = False;

    function __construct() {
        $this->load->helper('fuc');

        $this->load->library('topclass');
        parent::__construct();
    }

    function get_group_array($shopid) {//来自数据库
        $sql = "select * from groups where shopid =\"{$shopid}\"";
        $query = $this->db->query($sql);
        return $res = $query->result_array();
    }

    function get_group_bytopapi() {
        $grouparray = $this->topclass->api_getSellercenterRolesGetRequest("SellercenterRolesGetRequest", $_SESSION["usernick"], $_SESSION["sessionkey"]);
        objectToArray(&$grouparray);
      //  print_r($grouparray);exit;
        
        return $grouparray;
    }

    function get_rolechildaccounts_bytopapi($role_id) {
        $clientsarray = $this->topclass->api_getSellercenterRolemembersGetRequest("SellercenterRolemembersGetRequest", $role_id, $_SESSION["sessionkey"]);
        objectToArray(&$clientsarray);
        return $clientsarray;
    }

    function get_clients_array() {//来自api
        $grouparray = $this->topclass->api_SellercenterSubusersGetRequest("SellercenterSubusersGetRequest", $_SESSION["usernick"], $_SESSION["sessionkey"]);
        objectToArray(&$grouparray);

        if (isset($grouparray["subusers"]["sub_user_info"])) {
            return $grouparray["subusers"]["sub_user_info"];
        } else {
            return self::Statusflase;
        }
    }

    function get_childaccount($shopid) {
        $sql = "select * from  childaccount where shopid=\"{$shopid}\" ";
        $query = $this->db->query($sql);
        $resarray = $query->result_array();
        if (!empty($resarray)) {
            return $resarray;
        } else {
            return self::Statusflase;
        }
    }

    function get_seller_info($shopid) {//来自数据库，获取某个店铺全部客服记录
         $sql = "select groups.shopid,groups.groupname,groups.roleid,client.id,client.subid ,
childaccount.nicekname
from groups,client ,childaccount
where client.groupid=groups.roleid and childaccount.subid=client.subid
and childaccount.shopid=\"{$shopid}\"";
//groups.shopid=\"{$shopid}\""; //client.nickname,
        $query = $this->db->query($sql);
        return $res = $query->result_array();
    }

    function save_role($rolename) {
        $insetsql = "insert into groups(shopid,groupname)values(\"{$_SESSION["shopid"]}\",\"{$rolename}\")";
        $this->db->query($insetsql);
        $sql = "select * from groups  order by  id   desc  limit 1";
        $query = $this->db->query($sql);
        $res = $query->result_array();
        $id = $res[0]["id"];
        $updatesql = "update groups set roleid =\"@@{$id}\" where id={$id}";
        $this->db->query($updatesql);
    }

    function del_role($id) {
        echo $delsql = "delete from groups where id=\"{$id}\"";
        $this->db->query($delsql);
    }

    function update_role($postarray) {
        if(!is_numeric($postarray["groupId"])){
            
            return;
        }
        
         $updatesql = "update groups set groupname=\"{$postarray["groupName"]}\"
 where id=\"{$postarray["groupId"]}\" ";
        $this->db->query($updatesql);
    }

    function save_client($postarray) {
        $insetsql = "insert into client(shopid,groupid,subid)values(\"{$_SESSION["shopid"]}\",\"{$postarray["group"]}\",\"{$postarray["nicks"]}\")";

        $this->db->query($insetsql);
    }

    function delete_client($id) { //删除数据表client中的一条记录
        $delsql = "delete from client where id=\"{$id}\"";

        $this->db->query($delsql);
    }

    function import_data_new() {
        $sql = "select * from client where subid=0 and shopid=\"{$_SESSION["shopid"]}\"";
       
        $query = $this->db->query($sql);
        $res = $query->result_array();

        if (count($res) > 0) {
			
			//新增子帐号导入数据库  
			
			if( !($this->get_clients_array())) return true; //淘宝不存在小号，暂停执行
			
			$sql = "select * from childaccount where shopid=\"{$_SESSION["shopid"]}\" ";
			$query = $this->db->query($sql);
			$res = $query->result_array();
			foreach($res as $val){$subid[] = $val['subid'];}
			
			$clients_array = $this->get_clients_array();
			
			if(isset($clients_array[1])) :
				foreach($clients_array as $key => $val){
					if(in_array($val['sub_id'],$subid))
						unset($clients_array[$key]);
				}
			else :
				if(in_array($clients_array['sub_id'],$subid)) $clients_array = array();
				else  $clients_array = array(0 => $clients_array);
			endif;
			
			if(count($clients_array) > 0){
				 foreach ($clients_array as $key => $val) {
						$insertsql = "insert into childaccount (nicekname,subid,shopid) values(\"{$val["nick"]}\",\"{$val["sub_id"]}\",\"{$_SESSION["shopid"]}\")";
						$this->db->query($insertsql);
					}
			} // endif
			
			return true;
		}
		
        $sql = "delete from groups where shopid=\"{$_SESSION["shopid"]}\"";
        $this->db->query($sql);
        $sql = "delete from client where shopid=\"{$_SESSION["shopid"]}\"";
        $this->db->query($sql);
        $shpopid = $_SESSION["shopid"];
        $grouparray = $this->get_group_bytopapi();
        if (isset($grouparray["roles"]["role"])) {
            if (isset($grouparray["roles"]["role"][1])) {
                foreach ($grouparray["roles"]["role"] as $key => $val) {
                    $inssetsql = "INSERT INTO groups (shopid,groupname,roleid) VALUES (\"{$shpopid}\",\"{$val["role_name"]}\",\"{$val["role_id"]}\")";
                    // echo "<br>";
                    $this->db->query($inssetsql);
                }
            } else {
                //echo "这步判断返回数据格式，如果是单数组就遍历key role_id；role_name<br>";
                $inssetsql = "INSERT INTO groups (shopid,groupname,roleid) VALUES (\"{$shpopid}\",\"{$grouparray["roles"]["role"]["role_name"]}\",\"{$grouparray["roles"]["role"]["role_id"]}\")";
                $this->db->query($inssetsql);
            }
        } else {
            // echo "也就是api返回的为空数组，淘宝后台为设置角色分组请设置";
            // exit;
        }

        if (!($this->get_clients_array())) {
            //  echo "淘宝后台未设定小号，请设定后操作";
            //     exit;
        } else {

            $childclients = $this->get_clients_array();
            //删除
            $sql = "delete from childaccount where shopid=\"{$_SESSION["shopid"]}\"";
            $this->db->query($sql);
            if (isset($childclients[1])) {
                foreach ($childclients as $key => $val) {
                    $insertsql = "insert into childaccount (nicekname,subid,shopid) values(\"{$val["nick"]}\",\"{$val["sub_id"]}\",\"{$_SESSION["shopid"]}\")";
                    //  echo "<br>";
                    $this->db->query($insertsql);
                }
            } else {
                $insertsql = "insert into childaccount (nicekname,subid,shopid) values(\"{$childclients["nick"]}\",\"{$childclients["sub_id"]}\",\"{$_SESSION["shopid"]}\")";
                //echo "<br>";
                $this->db->query($insertsql);
            }}
            $insertsql = "insert into childaccount (nicekname,subid,shopid) values(\"{$_SESSION["usernick"]}\",\"0\",\"{$_SESSION["shopid"]}\")";
            $this->db->query($insertsql);
            $insertsql = "INSERT INTO groups (shopid,groupname) VALUES (\"{$shpopid}\",\"默认分组\")";
            $this->db->query($insertsql);
            $sql = "select id from groups order by id desc limit 1";
            $query = $this->db->query($sql);
            $res = $query->result_array();
            //  print_r($res );exit;

            $id = $res[0]["id"];
            $updatesql = "update groups set roleid =\"@@{$id}\" where id={$id}";
            $this->db->query($updatesql);
            $insertsql = "insert into client(shopid,groupid,subid)values(\"{$shpopid}\",\"{$id}\",0)";
            $this->db->query($insertsql);
        
    }

    function import_data() {
        //首先获取是否存在小号     
        if (!($this->get_clients_array())) {
            echo "淘宝后台未设定小号，请设定后操作";
            exit;
        } else {

            $childclients = $this->get_clients_array();
            //删除
            echo $sql = "delete from childaccount where shopid=\"{$_SESSION["shopid"]}\"";
            if (isset($childclients[1])) {
                foreach ($childclients as $key => $val) {
                    echo $insertsql = "insert into childaccount (nicekname,subid,shopid) values(\"{$val["nick"]}\",\"{$val["sub_id"]}\",\"{$_SESSION["shopid"]}\")";
                    echo "<br>";
                }
            } else {
                echo $insertsql = "insert into childaccount (nicekname,subid,shopid) values(\"{$childclients["nick"]}\",\"{$childclients["sub_id"]}\",\"{$_SESSION["shopid"]}\")";
                echo "<br>";
            }
            echo $insertsql = "insert into childaccount (nicekname,subid,shopid) values(\"{$_SESSION["usernick"]}\",\"0\",\"{$_SESSION["shopid"]}\")";
        }


        $shpopid = $_SESSION["shopid"];
        $sql = "select * from groups where shopid=\"{$shpopid}\"  ";
        $res = $this->db->query($sql);
        $resarray = $res->result_array();
//        if (!empty($resarray)) {
//            echo "数据库中已经倒入过数据不进行初始化，可以做出跳转";
//            exit;
//        }
        $grouparray = $this->get_group_bytopapi();
        if (isset($grouparray["roles"]["role"])) {

            echo "api得到的数组可以倒入数据库，表示淘宝后台做了角色的设定<br>";
            if (isset($grouparray["roles"]["role"][1])) {

                echo "这步判断返回数据格式，如果是多维数组就遍历key0，1，2，3.。。。<br>";
                foreach ($grouparray["roles"]["role"] as $key => $val) {
                    echo $inssetsql = "INSERT INTO groups (shopid,groupname,roleid) VALUES (\"{$shpopid}\",\"{$val["role_name"]}\",\"{$val["role_id"]}\")";
                    echo "<br>";

                    $clientsarray = $this->get_rolechildaccounts_bytopapi($val["role_id"]);


                    if (!empty($clientsarray)) {
                        if (isset($clientsarray["subusers"]["sub_user_info"][1])) {

                            echo "这个角色组包含的小号为多数组<br>";

                            foreach ($clientsarray["subusers"]["sub_user_info"] as $k => $v) {
                                echo $inssetsql = "INSERT INTO client (shopid,groupid,nickname,subid) VALUES
                             (\"{$shpopid}\",\"{$val["role_id"]}\",\"{$v["nick"]}\",\"{$v["sub_id"]}\")";
                                echo "<br>";
                            }
                        } else {

                            echo "这个角色组包含的小号为单数组<br>";


                            echo $inssetsql = "INSERT INTO client (shopid,groupid,nickname,subid) VALUES
                             (\"{$shpopid}\",\"{$val["role_id"]}\",\"{$clientsarray["subusers"]["sub_user_info"]["nick"]}\",\"{$clientsarray["subusers"]["sub_user_info"]["sub_id"]}\")";
                            echo "<br>";
                        }
                    } else {
                        echo "这个角色{$val["role_name"]}，下面没有设置的淘宝帐号是个空角色组，建议回到淘宝后台设置角色包含
                      的小号";
                        echo "<br>";
                    }
                }
            } else {

                echo "这步判断返回数据格式，如果是单数组就遍历key role_id；role_name<br>";
                echo $inssetsql = "INSERT INTO groups (shopid,groupname,roleid) VALUES (\"{$shpopid}\",\"{$grouparray["roles"]["role"]["role_name"]}\",\"{$grouparray["roles"]["role"]["role_id"]}\")";
                echo "<br>";

                $clientsarray = $this->get_rolechildaccounts_bytopapi($grouparray["roles"]["role"]["role_id"]);
                if (!empty($clientsarray)) {
                    if (isset($clientsarray["subusers"]["sub_user_info"][1])) {

                        echo "这个角色组包含的小号为多数组<br>";

                        foreach ($clientsarray["subusers"]["sub_user_info"] as $k => $v) {
                            echo $inssetsql = "INSERT INTO client (shopid,groupid,nickname,subid) VALUES
                             (\"{$shpopid}\",\"{$grouparray["roles"]["role"]["role_id"]}\",\"{$v["nick"]}\",\"{$v["sub_id"]}\")";
                            echo "<br>";
                        }
                    } else {

                        echo "这个角色组包含的小号为单数组<br>";


                        echo $inssetsql = "INSERT INTO client (shopid,groupid,nickname,subid) VALUES
                             (\"{$shpopid}\",\"{$grouparray["roles"]["role"]["role_id"]}\",\"{$clientsarray["subusers"]["sub_user_info"]["nick"]}\",\"{$clientsarray["subusers"]["sub_user_info"]["sub_id"]}\")";
                        echo "<br>";
                    }
                } else {
                    echo "这个角色{$grouparray["roles"]["role"]["role_name"]}，下面没有设置的淘宝帐号是个空角色组，建议回到淘宝后台设置角色包含
                      的小号";
                    echo "<br>";
                }
            }
        } else {


            echo "也就是api返回的为空数组，淘宝后台为设置角色分组请设置";

            exit;
        }
    }

}

?>
